package com.itheima.socket;

import java.io.InputStream;
import java.net.Socket;

/**
 * @Class: ServerSocket
 * @Package com.itheima.socket
 * @Description: 定义服务端Socket
 * @Company: http://www.itheima.com/
 */
public class BioServerSocket {
    public static void main(String[] args) throws Exception {
        //创建ServerSocket对象，用于客户端的连接
        java.net.ServerSocket serverSocket = new java.net.ServerSocket(8080);
        //定义输入流对象读取数据
        byte[] bytes = new byte[1024];
        try {
            
            while (true) {
                System.out.println("服务端发生阻塞，等待连接....");
                //调用accept方法监听客户端，阻塞方法
                Socket accept = serverSocket.accept();
                //调用Socket对象的方法获取输入流对象
                InputStream inputStream = ((Socket) accept).getInputStream();
                System.out.println("服务端发生阻塞，等待接收数据....");
                int read = inputStream.read(bytes);
                System.out.println(new String(bytes, 0, read));
                //关闭资源
                accept.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        }
    }
}
